﻿using Application.ProductTypeService;
using AutoMapper;
using Domain.Entity;
using Domain.Entity.bs;
using Domain.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Application.ProductService
{
    public class ProductService : IProductService
    {
        private readonly IProductRepository productRepository;
        private readonly IStockRepository stockRepository;
        private readonly IMapper mapper;

        public ProductService(IProductRepository productRepository,IMapper mapper, IStockRepository stockRepository)
        {
            this.productRepository = productRepository;
            this.stockRepository = stockRepository;
            this.mapper = mapper;
        }

        //添加货品信息
        public async Task<int> AddProduct(AddProductDto addProductDto)
        {
            //转换
            Product product = mapper.Map<Product>(addProductDto);
            return await productRepository.AddProduct(product);
        }

        //删除货品信息
        public async Task<int> DeleteProduct(int id)
        {
            return await productRepository.DeleteProduct(id);
        }

        //分页高级查询
        public async Task<FenYe<Product>> GetAdvancedProduct(FenYe<Product> fenYe, string? code, string? name, string? typeid, string? model, string? unit, string? startinprice, string? endinprice, string? startoutprice, string? endoutprice, int? is_datamanagement, int? status, int? startwarningdays, int? endwarningdays, int? whid, string? barcode, string? starttime, string? endtime, string? createname)
        {
            return await productRepository.GetAdvancedProduct(fenYe, code, name, typeid, model, unit, startinprice, endinprice, startoutprice,endoutprice, is_datamanagement, status, startwarningdays, endwarningdays, whid, barcode, starttime, endtime, createname);
        }

        //查询所有货品信息
        public async Task<List<Product>> GetAllProduct()
        {
            return await productRepository.GetAllProduct();
        }

        //分页查询货品信息
        public async Task<FenYe<Product>> GetProduct(FenYe<Product> fenYe, string? name, bool? inventory, int? whid, string? type)
        {
            return await productRepository.GetProduct(fenYe,name,inventory,whid,type);
        }

        //根据id查询货品信息
        public async Task<Product> GetProductById(int id)
        {
            return await productRepository.GetProductById(id);
        }

        //更新货品总库存与总金额
        public async Task<int> Updateinventory(UpdateinventoryDto updateinventoryDto)
        {
            Product product=mapper.Map<Product>(updateinventoryDto);
            return await productRepository.Updateinventory(product);
        }


        ////更新货品总库存与总金额(出库)
        public async Task<int> UpdateinventoryJian(UpdateinventoryDto updateinventoryDto)
        {
            Product product = mapper.Map<Product>(updateinventoryDto);
            return await productRepository.UpdateinventoryJian(product);
        }


        //修改货品计划可用库存
        public async Task<int> Updateky(int id, int inventory)
        {
            return await productRepository.Updateky(id, inventory);
        }

        //修改货品信息
        public async Task<int> UpdateProduct(UpdateProductDto updateProductDto)
        {
            //转换
            Product product = mapper.Map<Product>(updateProductDto);
            return await productRepository.UpdateProduct(product);
        }

        //修改货品信息状态（启用/停用）
        public async Task<int> UpdateStatus(int procid, int status)
        {
            return await productRepository.UpdateStatus(procid, status);
        }

        //根据货品id批量获取
        public async Task<List<Product>> GetProductsByIds(int[] proc_ids)
        {
            return await productRepository.GetProductsByIds(proc_ids);
        }

        //通过查询到的库存查货物
        public async Task<FenYe<ProductWithStocks>> GetProductsByIds(int CurrentPage, int wh_id, string? proc_code, string? proc_primary_unit)
        {
            // 获取当前仓库的所有库存记录
            List<Stock> allStocks = await stockRepository.GetStockwhid(wh_id);

            // 提取仓库中所有存在的货品ID（去重）
            int[] distinctProductIds = allStocks
                .Select(s => s.proc_id)
                .Distinct()
                .ToArray();

            // 如果没有货品，返回空结果
            if (!distinctProductIds.Any())
            {
                return new FenYe<ProductWithStocks>
                {
                    CurrentPage = CurrentPage,
                    PageSize = 10, // 默认分页大小
                    List = new List<ProductWithStocks>(),
                    Rows = 0
                };
            }

            // 创建分页对象并查询货品
            FenYe<Product> fenYeProduct = new FenYe<Product>
            {
                CurrentPage = CurrentPage,
            };

            // 使用之前的方法查询货品（带分页）
            fenYeProduct = await productRepository.GetProductsByIds(fenYeProduct, distinctProductIds, proc_code,proc_primary_unit);

            // 获取当前页的货品ID
            var currentPageProductIds = fenYeProduct.List.Select(p => p.proc_id).ToArray();

            // 获取当前页货品对应的所有库存记录（按货品ID分组）
            var stocksByProduct = allStocks
                .Where(s => currentPageProductIds.Contains(s.proc_id))
                .GroupBy(s => s.proc_id)
                .ToDictionary(g => g.Key, g => g.ToList());

            // 构建返回结果
            var result = new FenYe<ProductWithStocks>
            {
                CurrentPage = fenYeProduct.CurrentPage,
                PageSize = fenYeProduct.PageSize,
                Rows = fenYeProduct.Rows,
                List = new List<ProductWithStocks>()
            };

            // 组装货品及其对应的库存记录
            foreach (var product in fenYeProduct.List)
            {
                result.List.Add(new ProductWithStocks
                {
                    Product = product,
                    Stocks = stocksByProduct.TryGetValue(product.proc_id, out var stocks)
                             ? stocks
                             : new List<Stock>()
                });
            }

            return result;
        }
    }
}
